"""
Save the message sent by the user and deliver javascript page.
"""

import chatLogic
from whiff import whiffenv
from whiff import resolver
import sys

class saveMessage:
    def __init__(self, page):
        self.page = page
    def __call__(self, env, start_response):
        #pr "save message called"
        #chatConnection = chatLogic.test_gadfly_connection(whiffenv.getId(env, "DbPrefix"))
        chatConnection = chatLogic.getConnection(env)
        error = None
        nick = chatLogic.getCookieValue(env)
        if nick and not chatConnection.validateNick(nick):
            error = "Nick is not logged in: "+repr(nick)
            nick = None
            #pr "no valid nick", repr(nick)
        env = resolver.process_cgi(env)
        cgi_dict = env[whiffenv.CGI_DICTIONARY]
        messages = cgi_dict.get("MessageInMessage")
        #pr "messages and nick", (messages, nick)
        if messages and nick:
            message = messages[0].strip()
            if message:
                try:
                    (rid, roomInfo, view) = chatConnection.getRoomInfoForNick(nick)
                except "bogus":
                    error = "could not get room information for: "+repr(nick)
                else:
                    #pr "recording message", (nick, rid, message)
                    chatConnection.cleanRoom(rid)
                    chatConnection.commit()
                    try:
                        chatConnection.say(nick, rid, message)
                    except:
                        error = "say operation failed "+repr(sys.exc_info())
                    else:
                        chatConnection.commit()
        else:
            #pr "invalid message"
            if not messages:
                pass # ignore missing message (not an error)
            elif not nick:
                if not error:
                    error = "could not determine nick name"
            else:
                raise ValueError, "unreachable code"
        if error:
            # replace the message in area with login request
            #pr "setting error", error
            env = env.copy()
            whiffenv.setId(env, "ChangeMessageIn", True)
            env["whiff.chat.login_error"] = error+":: "
        result =  list(self.page(env, start_response))
        #pr "sending"
        #pr "".join(result)
        return result

__middleware__ = saveMessage
